const Router = require('@koa/router')
const proxy = require('koa-better-http-proxy')

const router = new Router()
/**
 * 微信公众号文章阅读劫持
 */
const handleProxy = proxy('https://mp.weixin.qq.com', {
  // 修改请求头
  proxyReqOptDecorator(proxyReqOpts) {
    // 添加或修改请求头
    proxyReqOpts.headers.Host = 'mp.weixin.qq.com'
    delete proxyReqOpts.headers.cookie
    return proxyReqOpts
  },
  userResHeadersDecorator(headers) {
    // 修改返回头
    delete headers['set-cookie']
    delete headers['content-security-policy']
    delete headers['content-security-policy-report-only']
    return headers
  },
  // 修改返回内容
  userResDecorator(proxyRes, proxyResData) {
    const data = proxyResData.toString('utf8')
    // 这里可以根据需要修改返回的内容
    return (
      data
        .replace(
          /\<head\>/g,
          `<head><meta name="referrer" content="no-referrer" /><style>.video_iframe{display: block!important}.video_iframe+.wx_widget_placeholder{display: none!important}</style>`
        )
        .replace(/origin-when-cross-origin/g, 'no-referrer')
        .replace(/strict-no-referrer/g, 'no-referrer')
        // crossorigin="anonymous"
        .replace(/crossorigin="anonymous"/g, '')
        //  将data中以//res.wx.qq.com开头，js结尾的链接  替换为/res开头的链接
        .replace(
          /\/\/res\.wx\.qq\.com.*?\.js/g,
          match => `/res${match.substring(15)}`
        )
        // http://mpvideo.qpic.cn  替换为 /video
        .replace(/http:\/\/mpvideo\.qpic\.cn/g, '/video')
        // background-image: url(&quot;https://mmbiz.qpic.cn 替换为/img
        .replace(
          /background-image: url\(&quot;https:\/\/mmbiz\.qpic\.cn/g,
          `background-image: url(&quot;/img`
        )
        // cover_url: 'http://mmbiz.qpic.cn 替换为/img
        .replace(/cover_url: 'http:\/\/mmbiz\.qpic\.cn/g, `cover_url: '/img`)
    )
  }
})

router.get(/^\/s/, handleProxy)

module.exports = router.routes()
